import java.util.PriorityQueue;
import java.util.concurrent.Executors;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;
    //要执行任务的时刻
    private long time;
    public MyTimerTask(Runnable task,long time){
        this.task = task;
        this.time = time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }

    public long getTime(){
        return time;
    }

    public void run(){
        task.run();
    }
}

//自己实现一个定时器
class MyTimer{
    private Object locker = new Object();
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private long delay;

    public void schedule(Runnable task,long delay){
        synchronized (locker){
            MyTimerTask task1 = new MyTimerTask(task,delay + System.currentTimeMillis());
            queue.offer(task1);
            locker.notify();
        }

    }

    public MyTimer(){
        Thread thread = new Thread(() -> {
               while (true){
                   synchronized (locker){
                       while (queue.isEmpty()){
                           try {
                               locker.wait();
                           } catch (InterruptedException e) {
                               throw new RuntimeException(e);
                           }
                       }
                       MyTimerTask task = queue.peek();
                       if (task.getTime() > System.currentTimeMillis()){
                           //时间没到，继续等待
                           try {
                               locker.wait(task.getTime() - System.currentTimeMillis());
                           } catch (InterruptedException e) {
                               throw new RuntimeException(e);
                           }
                       }else {
                           //时间到了，开始执行
                           task.run();
                           queue.poll();
                       }
                   }
           }
        });
        thread.start();
    }

}

public class Demo9 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        },1000);

        System.out.println("hello main");
        Executors.newScheduledThreadPool(4);
    }
}
